package com.zenchn.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.zenchn.entity.HttpResult;
import com.zenchn.utils.ObjectUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 *
 * @author panbingqi
 * @date 2021-06-01
 */
public class ShiroExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        HttpResult result = new HttpResult(httpServletRequest.getRequestURI());
        if (ex instanceof IllegalArgumentException) {
            result.setMessage(ex.getMessage());
            result.setStatus(HttpStatus.BAD_REQUEST.value());
            result.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
            httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());

        } else if (ex instanceof UnauthenticatedException) {
            result.setMessage("拒绝访问,Authorization 授权码错误.");
            result.setStatus(HttpStatus.FORBIDDEN.value());
            result.setError(HttpStatus.FORBIDDEN.getReasonPhrase());
            httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());

        } else if (ex instanceof UnauthorizedException) {
            result.setMessage("未授权-当前账号无法使用该功能.");
            result.setStatus(HttpStatus.UNAUTHORIZED.value());
            result.setError(HttpStatus.UNAUTHORIZED.getReasonPhrase());
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());

        } else if (ex instanceof CheckException || ex instanceof CustomException) {
            ex.printStackTrace();
            result.setMessage(ex.getMessage());
            result.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
            result.setError(HttpStatus.NOT_ACCEPTABLE.getReasonPhrase());
            httpServletResponse.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
        } else {
            result.setMessage("服务器内部错误，请联系相关人员.");
            result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setError(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        view.setAttributesMap(ObjectUtils.transAllBeanToMap(result));
        mv.setView(view);
        return mv;
    }
}
